import _ from "lodash";
interface IParams {
    [key: string]: any;
}

/**
 * 对象转为URL参数字符串
 * @param params
 * @param url
 * @returns url字符串
 */

export const getParamsToUrl = (params: IParams, url: string) => {
    const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join("&");
    return !!url ? `${url}?${queryString}` : queryString;
};

/**
 *
 * @param url url字符串
 * @returns 以key-value形式返回url参数对象
 */

export const getUrlAllParams = (url: string): object => {
    const urlParams = new URLSearchParams(url);
    const params: IParams = {};
    urlParams.forEach((value, key) => {
        params[key] = value;
    });
    return params;
};

/**
 *
 * @param name search参数名
 * @param url url字符串 默认取当前页面url
 * @returns 返回search参数值
 */
export const getUrlParams = (name: string, url?: any): any =>
    new URL(url || globalThis.location.href).searchParams.get(name);

/**
 *
 * @param arr  数组
 * @param filter 查找条件 必须是一个对象
 * @param name 可选 如果传入的话 返回的是符合条件的对象中指定属性的值
 * @returns 返回最后一个符合条件的对象或对象中指定属性的值
 */
export const findArrayItem = (arr: any[], filter: IParams, name?: string) => {
    let curItem: any = {};
    arr.forEach((item: any) => {
        let count = 0;
        const filterKeys = Object.keys(filter);
        filterKeys.forEach((key: string) => {
            if (item[key] === filter[key]) {
                count += 1;
            }
        });
        if (count === filterKeys.length) {
            curItem = item;
        }
    });
    return name ? curItem[name] : curItem;
};

/**
 * 主要用来在react组件的memo中调用
 * @param oldVal memo 第一参数
 * @param newVal memo 第二参数
 * @param key?  key不传 默认深层次比较  传单个 单个比较 传多个是以数组字符串形式
 * @returns  bool
 */

export const memoCallBack = (oldVal: any, newVal: any, key = null) => {
    if (_.isNull(key)) {
        return _.isEqual(oldVal, newVal);
    } else if (_.isString(key)) {
        return _.isEqual(oldVal[key], newVal(key));
    } else if (_.isArray(key)) {
        const oldObj: any = {};
        const newObj: any = {};
        _.forEach(key, (val: string) => {
            oldObj[val] = oldVal[val];
            newObj[val] = oldVal[val];
        });
        return _.isEqual(oldObj, newObj);
    }
};
